package adapters

import (
	"context"
	"docker-monitor/internal/mcp/core"
	"docker-monitor/internal/mcp/handlers"
	"log"
	"time"
)

// MCPIntegration 处理MCP服务的集成
// port 参数用于指定MCP服务器监听的端口
func MCPIntegration(ctx context.Context, cancel context.CancelFunc, port string) *core.MCPServer {
	// 创建MCP服务器
	server, err := core.NewMCPServer()
	if err != nil {
		log.Fatalf("Failed to create MCP server: %v", err)
	}

	// 注册工具
	handlers.SetupTools(server)

	// 注册资源
	handlers.SetupResources(server)

	// 注册提示词
	handlers.SetupPrompts(server)

	// 启动MCP服务器
	if err := server.Start(port); err != nil {
		log.Fatalf("Failed to start MCP server: %v", err)
	}

	// 监听退出信号，优雅关闭MCP服务器
	go func() {
		<-ctx.Done()
		shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer shutdownCancel()

		if err := server.Shutdown(shutdownCtx); err != nil {
			log.Printf("Failed to shutdown MCP server gracefully: %v", err)
		}
	}()

	return server
}